package com.example.hotelsystm.service;

import com.example.hotelsystm.model.Hotel;
import com.example.hotelsystm.repository.HotelRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

@Service
public class HotelServiceLmpl implements HotelService {
    @Autowired
    private HotelRepository hotelRepository;

    @Override
    public List<Hotel> getAllHotel() {
        return hotelRepository.findAll();
    }

    @Override
    public void saveHotel(Hotel hotel) {
        hotelRepository.save(hotel);
    }

    //通过name来查询数据
    @Override
    public List<Hotel> findByRoomContaining(String name) {
        List<Hotel> roomlist = hotelRepository.findHotelBy(name);

        return roomlist;
    }

    @Override
    public Hotel getHotelByid(Long id) {
        Optional<Hotel> optional = hotelRepository.findById(id);
        Hotel hotel = null;
        if( optional.isPresent()){
            hotel = optional.get();
        }else{
            throw new RuntimeException(" 查无此人，请重输入, id :  "+ id);
        }
        return hotel;
    }


    @Override
    public void deleteHotelByid(Long id) {
        this.hotelRepository.deleteById(id);

    }

    @Override
    public Page<Hotel> findPaginated(int pageNo, int pageSize, String sortField, String sortDirection) {
        //设置排序参数，升序ASC/降序DESC？
        Sort sort = sortDirection.equalsIgnoreCase(Sort.Direction.ASC.name())
                ? Sort.by(sortField).ascending()
                : Sort.by(sortField).descending();

        //根据页号/每页记录数/排序依据返回某指定页面数据。
        Pageable pageable = PageRequest.of(pageNo - 1, pageSize, sort);
        return this.hotelRepository.findAll(pageable);
    }

}
